package controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //这些优化其实是SpringMVC差不多
        request.setCharacterEncoding("UTF-8");//所有继承他的都可以处理乱码了
        String methodName = request.getParameter("method");
        //反射获取方法
        try {
            Method method=this.getClass().getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);//后边这俩是形参，按照顺序写好
            if (method != null) {
                String url = (String)method.invoke(this,request,response);
                if(url==null||url.trim().length()==0){ //前端转发 重定向 json处理  //为空字符串，或者只包含空白字符
                    return;
                }
                //转发重定向
                if(url.startsWith("redirect:")){//重定向，就是个标识符，aa也可   "redirect:/index.jsp"
                    String redirectURL = url.substring(url.indexOf(":") + 1);
                    response.sendRedirect(request.getContextPath()+redirectURL);//相对路径不能写/
                }else{//转发  /index.jsp
                    request.getRequestDispatcher(url).forward(request,response);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}



